import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel
from xml.etree import ElementTree as ET

class XMLUILoader:
    def __init__(self, xml_path):
        self.xml_path = xml_path
        self.window = None
        self.layout = None

    def load(self):
        tree = ET.parse(self.xml_path)
        root = tree.getroot()

        # 创建主窗口
        self.window = QWidget()
        self.window.setWindowTitle(root.get('title', 'PyGUIXml App'))
        width = int(root.get('width', 800))
        height = int(root.get('height', 600))
        self.window.setFixedSize(width, height)

        # 解析布局
        layout_node = root.find('layout')
        if layout_node is not None:
            layout_type = layout_node.get('type', 'QVBoxLayout')
            if layout_type == 'QVBoxLayout':
                self.layout = QVBoxLayout()
            else:
                raise NotImplementedError(f'不支持的布局类型: {layout_type}')

            # 解析子控件
            for widget_node in layout_node.findall('widget'):
                self._parse_widget(widget_node)

            self.window.setLayout(self.layout)
        return self.window

    def _parse_widget(self, node):
        widget_type = node.get('type')
        if widget_type == 'QLabel':
            label = QLabel()
            label.setText(node.get('text', ''))
            alignment = node.get('alignment')
            if alignment:
                from PyQt5.QtCore import Qt
                align_flags = getattr(Qt, alignment, Qt.AlignCenter)
                label.setAlignment(align_flags)
            self.layout.addWidget(label)
        else:
            raise NotImplementedError(f'不支持的控件类型: {widget_type}')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    loader = XMLUILoader('ui/index.xml')
    main_window = loader.load()
    main_window.show()
    sys.exit(app.exec_())